/*
 * @Author: sunzhongjie
 * @Date: 2020-11-27 16:41:41
 * @LastEditors: Jelly
 * @LastEditTime: 2020-12-17 19:00:53
 */
var express = require('express'),
    app = express(),
    path = require("path"),
    fs = require("fs"),
    redis = require('./util/redis.js'),
    { REDIS_DB } = require('./util/config').dev;

const rootPath =
  process.env.NODE_ENV === "production"
  ? "/var/www/www.happyeasygo.com"
  : path.resolve(__dirname, "../build");

// 获取对应活动文件数据
function getFile(pagePath) {
  if(!fs.existsSync(pagePath)) {
    console.log('No dir', pagePath);
    return
  }
  const filePath = path.resolve(pagePath, "index.html");
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, "utf8", function (err, data) {
      if (err) {
        return reject();
      }
      // data: 整个html文件内容
      return resolve(data);
    });
  });
}
// 更改对应活动 index.html 中 meta里 <? ?>
app.get(`/offer-templet`, (req, res) => {
  const pageName = req.params.pageName || 'mega-flight-sale';
  Promise.all([
    getFile(`${rootPath}/offer-templet`),
    redis.hget(REDIS_DB, pageName)
  ]).then(([file, obj]) => {
    console.log(obj)
    obj = obj || {};
    // 替换html
    // const linkTag = file.match(/<meta[^/]+?>/gi)
    // console.log(linkTag)
    const result = file.replace(/<\?([^?]+)\?>/g, function (all, group) {
       console.log(all, '/', group)
      return obj[group] || "";
    });
    res.send(result);
  }).catch(err => {
    console.log(err);
    return res.status(500);
  })
})
app.use(express.static(path.resolve(__dirname, "../build")));
app.listen(3000, () => console.log(`服务已就绪!`));
